package com.serverapk.camera;

import android.util.Log;

import com.serverapk.PostNex;
import com.serverapk.interfaces.MediaStreamListener;
import com.serverapk.interfaces.OkHttpCallbackListener;
import com.serverapk.para.Common;
import com.serverapk.socket.SocketUtil;
import com.serverapk.util.L;
import com.serverapk.util.Tool;

//import net.sf.json.JSONObject;
import org.apache.commons.lang.RandomStringUtils;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * 摄像头接口
 *
 * @author Administrator
 */
public class CameraService {
    private String TAG = "CameraService";
    private boolean recvjson = true;
    static final int READ_BUF_LEN = 1024 * 1024;
    private int gcount = 0;
    private File file;

    /**
     * 获取图片
     */
    public void getPicture(final Map<Integer, SocketUtil> socketMap, final MediaStreamListener mediaListener) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    boolean imgFlag = true;
                    for (int i = 0; i < socketMap.size(); i++) {
                        boolean connflag = socketMap.get(i).waitForConnect();
                        if (connflag) {
                            sendStartMsg(socketMap.get(i));
                            if (getStartMsgRes(socketMap.get(i)) == MediaStream.MEDIA_RES_SUCESS) {
                                imgFlag = recvMediaStream(socketMap.get(i), i);
                                if (imgFlag) {
                                    socketMap.get(i).sockStop();
                                }
                            }
                        } else {
                            mediaListener.onError(Common.error_code1, Common.error_info1);
                        }
                    }
                    if (imgFlag) {
                        mediaListener.onFinish("get_picture_success");
                    } else {
                        mediaListener.onError(Common.error_code2, Common.error_info2);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    if (mediaListener != null) {
                        mediaListener.onError(Common.error_code3, Common.error_info3);
                    }
                }
            }
        }).start();

    }

    /**
     * 上传图片
     *
     * @param imgList
     * @return
     */

    List<String> sendPicResult;

    public void sendPicture(final List<String> imgList, final OkHttpCallbackListener okHttplListener) {
        final long cu = System.currentTimeMillis();
        new Thread(new Runnable() {
            public void run() {
                sendPicResult = new ArrayList<String>();
                sendPicResult.clear();
                OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
                OkHttpClient okhttpClient = okHttpBuilder.build();

                //提交图片数据
                for (int i = 0; i < imgList.size(); i++) {
//		        	MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
//			        //提交字段数据
//			        builder.addFormDataPart("api_key", Common.camera_api_key);
//			        builder.addFormDataPart("secret_key", Common.camera_secret_key);
//		        	File file = new File(imgList.get(i));
//		            System.out.println(file.getAbsolutePath());
//		            RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"), file);
//		            builder.addFormDataPart("image_file", file.getName(), fileBody);
//
//		            MultipartBody multipartBody = builder.build();
//			        Request request = new Request.Builder().url(Common.camera_url).post(multipartBody).build();
//			        Response response;

                    try {
                        JSONObject json = new JSONObject();
                        if (!Common.camera_url.contains("nex.ren"))
                            json.put("base64_image", Tool.GetImageStr_Base64(imgList.get(i)));
                        else {
                            json.put("image", Tool.GetImageStr_Base64(imgList.get(i)));
                            json.put("uuid", Common.imei + "-" + System.currentTimeMillis());
                            json.put("imagetype", "jpg");
                        }
                        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), String.valueOf(json));
                        //TODO 刚改的 吧token放到header里面
//                        Request request = new Request.Builder().url("https://deploy.seetatech.com/api")
//                                .addHeader("Authorization", "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJkZXBsb3lJZCI6MzIyfQ.lM6mKgStVg9q9svN3aMqTtXkRmNWQ-e6xqB6xsVdhPhSwphZzgpOSX4m533_oAsLIvSy3iE0lFNp2pYyXKdpLA")
//                                .post(requestBody).build();

//						Request request = new Request.Builder().url("http://218.94.122.141:14011")
//								.post(requestBody).build();

                        L.e("Common.camera_url=" + Common.camera_url);
                        Request request = new Request.Builder().url(Common.camera_url)
                                .post(requestBody).build();

                        Response response;

                        String result = "";
                        response = okhttpClient.newCall(request).execute();
                        result = response.body().string().toString();
                        L.e("result=" + result);
                        if (result != null && !"".equals(result)) {
                            sendPicResult.add(result);
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        L.e("e==" + e.toString());
                        e.printStackTrace();
                        if (okHttplListener != null) {
                            okHttplListener.onError(Common.error_code4, Common.error_info4);
                        }
                    }
                }

                if (sendPicResult.size() == Common.cameraIp.size()) {
                    long end = System.currentTimeMillis();
                    okHttplListener.onError(Common.error_code8, "识别时间:" + (end - cu) + "ms");
                    if (okHttplListener != null) {
                        okHttplListener.onFinish(sendPicResult);
                    }
                } else {
                    if (okHttplListener != null) {
                        okHttplListener.onError(Common.error_code4, Common.error_info4);
                    }
                }

            }
        }).start();
    }


    public void sendStartMsg(SocketUtil socketUtil) {
        JsonHandle jsonHandle = new JsonHandle();
        String msg = jsonHandle.getJsonMsg();
        socketUtil.writeSockData(msg.getBytes());
    }

    public int getStartMsgRes(SocketUtil socketUtil) {
        int result_code = 0;
        byte[] media_res = new byte[MediaStream.MEDIA_RES_BUF_LEN];
        if (socketUtil.readSockData(media_res) == MediaStream.MEDIA_RES_BUF_LEN) {
            MediaStream mediaStream = new MediaStream();
            result_code = mediaStream.parseMediaRes(media_res);
        }
        Log.d(TAG, System.currentTimeMillis() + " verify result_code:" + result_code);
        return result_code;
    }

    public boolean recvMediaStream(SocketUtil socketUtil, int i) {
        int pic_len = 0;
        boolean ret = false;

        byte[] media_hdr = new byte[MediaStream.MEDIA_HDR_BUF_LEN];
        MediaStream mediaStream = new MediaStream();
        recvjson = true;
        while (recvjson) {
            if (socketUtil.readSockData(media_hdr) <= 0)
                break;
            pic_len = mediaStream.parseMediaHdr(media_hdr);
            Log.d(TAG, "=====> hdr_len:" + pic_len);
            if (pic_len > 0) {
                String filename = Common.filepath + i + ".jpg";
                file = new File(filename);
                if (file.exists()) {
                    file.delete();
                }
                try {
                    FileOutputStream fos = new FileOutputStream(filename);
                    byte[] data = new byte[READ_BUF_LEN];
                    int tmp_len = 0;
                    int real_len = 0;
                    while ((tmp_len = socketUtil.readSockData(data)) != -1) {
                        real_len += tmp_len;
                        fos.write(data, 0, tmp_len);
                        if (pic_len == real_len) {
                            ret = true;
                            break;
                        } else if (pic_len - tmp_len < READ_BUF_LEN) {
                            data = new byte[pic_len - real_len];
                        }
                    }
                    Log.d(TAG, "=====> Write2flash:" + real_len);
                    fos.flush();
                    fos.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                break;
            }
            gcount++;
            recvjson = false;
        }
        return ret;
    }

}
